package com.example.demo.service;

import com.example.demo.mapper.CourseNumMapper;
import com.example.demo.mapper.ScoreMapper;
import com.example.demo.mapper.Score_CopyMapper;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.entity.*;
import com.example.demo.util.KMeansRunUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class ClusterService {
    @Autowired
    private  ScoreMapper sm;
    @Autowired
    private  StudentMapper stm;
    @Autowired
    private  CourseNumMapper cnm;
    @Autowired
    private  Score_CopyMapper scm;

    private ReentrantLock lock = new ReentrantLock();

    public Set<Cluster> initData(String term, List<Integer> need) {
        Map<Integer, float[]> map = new HashMap<>();
        List<Student> alllStu = stm.selectStudentByIds(need);
        for (Student s : alllStu) {
            List<Score_copy> scoreByTermAndId = scm.findScoreByTermAndId(s.getId(), term);
            if (scoreByTermAndId.size() != 0) {
                System.out.println(s.getId() + "===" + term);
                //TODO 临时放开
                CourseNum courseNum = cnm.selectCourseNumByIdAndTerm(s.getId(), term);
                float[] score = new float[scoreByTermAndId.size() + 1];
                for (int i = 0; i < scoreByTermAndId.size(); i++) {
                    score[i] = scoreByTermAndId.get(i).getFscore();
                }
                map.put(s.getId(), score);
            }
        }
        lock.lock();
        KMeansRunUtil kmr;
        Set<Cluster> clusterSet;
        try {
            kmr = new KMeansRunUtil(3, map);
            clusterSet = kmr.run();
        } finally {
            lock.unlock();
        }
        System.out.println("单次迭代运行次数：" + kmr.getIterTimes());
        for (Cluster cluster : clusterSet) {
            System.out.println(cluster);
        }
        return clusterSet;
    }
}
